package com.guet.imageAndVideo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guet.common.entity.MyAppConfig;
import com.guet.common.entity.PageDataVO;
import com.guet.common.entity.PageVO;
import com.guet.common.exception.ApiException;
import com.guet.imageAndVideo.beans.entity.Image;
import com.guet.imageAndVideo.mapper.ImageMapper;
import com.guet.imageAndVideo.service.IImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.List;

/**
 * @author Li
 * @create 2022-12-16-21:45
 */
@Service
public class ImageServiceImpl implements IImageService {

    @Autowired
    ImageMapper imageMapper;

    @Autowired
    MyAppConfig myAppConfig;

    @Override
    public void add(Integer userId, Integer issueId, String url) {
        imageMapper.add(userId, issueId, url);
    }


    @Override
    public PageDataVO<Image> select(Integer userId, PageVO pageVO) {

        PageHelper.startPage(pageVO.getPageNum(), pageVO.getPageSize());
        List<Image> list = imageMapper.find(userId);

        PageInfo pageInfo = new PageInfo(list);
        PageDataVO pageDataVO = new PageDataVO();
        pageDataVO.setItems(pageInfo.getList());
        pageDataVO.setPageNum((long) pageInfo.getPageNum());
        pageDataVO.setPageSize((long) pageInfo.getPageSize());
        pageDataVO.setTotalItem(pageInfo.getTotal());
        pageDataVO.setTotalPage((long) pageInfo.getPages());

        return pageDataVO;

    }

    @Override
    public void delete(Integer userId, List<Integer> imageIds) {

        for (Integer imageId : imageIds) {
            Image image = imageMapper.select(userId, imageId);
            if (image == null) {
                throw new ApiException("照片不允许操作");
            }

            imageMapper.delete(userId, imageId);

            String url = image.getImageUrl().substring(image.getImageUrl().lastIndexOf("/") + 1);

            File file = new File(myAppConfig.getSaveFilePath() + url);

            file.delete();

        }

    }


}
